let pageData = {
    "current": 1,
    "optimizeCountSql": true,
    "orders": [],
    "pages": 2,
    "records": [{
        "category": {
            "id": 1,
            "name": "食品类"
        },
        "categoryId": 1,
        "createTime": 1537475727000,
        "detail": "百草味手撕面包（原味)1000g商品毛重：1.0kg商品产地：浙江省杭州市口味：原味包装形式：箱装类别：手撕面包净含量：501g-1kg",
        "id": 1,
        "img": "https://img14.360buyimg.com/n1/jfs/t1/196223/7/24898/247568/628370b0E70c316de/7ed05094babd66c0.jpg",
        "name": "百草味 手撕面包1000g/箱 原味整箱办公室早餐休闲食品面包点心零食",
        "price": 22.9,
        "productId": 4,
        "stock": 981
    }],
        "searchCount": true,
        "size": 8,
        "total": 16
}
let $entry_product = $('#admin-card-product-list-entry')
let $entry_pages = $('#admin-card-product-pages-entry')
function renderProducts(products, delay){
    $entry_product.html('')
    setTimeout(function (){
        products.forEach(function (product, index){
            let fn_modify = "renderEditModal(this, " + product['id'] + ")"
            let fn_show = "renderShowModal(this, " + product['id'] + ")"
            let fn_remove = "removeProduct(" + product['id'] + ")"
            $entry_product.append(`
            <tr valign="baseline">
                <td><input type="checkbox" class="cb_product" data-id="${product['id']}" style="width: 20px; height: 20px;"></td>
                <td>${product['id']}</td>
                <td>${product['name']}</td>
                <td>${product['category']['name']}</td>
                <td><img src="${product['img']}" class="w-100"></td>
                <td class="ms-text-cut-5">${product['detail']}</td>
                <td>${product['stock']}</td>
                <td>
                     <button class="btn btn-primary w-25" data-bs-toggle="modal" data-bs-target="#modal-show" onclick="${fn_show}">查看</button>
                     <button class="btn btn-warning w-25" data-bs-toggle="modal" data-bs-target="#modal-base" onclick="${fn_modify}">编辑</button>
                     <button class="btn btn-danger w-25" onclick="${fn_remove}">删除</button>
                </td>
          </tr>
        `)
        })
    }, delay)
}
////////////////////// 渲染页面区  ///////////////////////

function renderPage(page){
    $entry_pages.html('')
    let $perPage = $(`<li></li>`)
    // 渲染尾部
    let $tail = `<li class="align-self-center r">
                &nbsp;&nbsp;到第&nbsp;&nbsp;
            </li>
            <li class="align-self-center">
                <input id="admin-user-input-to-page" class="input-group" name="pageNum" size="5">
            </li>
            <li class="align-self-center">
                &nbsp;页&nbsp;
            </li>
            <li class="align-self-center">
                <button class="btn btn-outline-dark" onclick="toPage('admin-user-input-to-page', 1, ${page.pages})">确定</button>
            </li>`

    // 计算页数的渲染范围
    page.prePage = Math.max(1, page['current']- 1)
    page.nextPage = Math.min(page['pages'], page['current'] + 1)
    page.startPage = Math.max(1, page['current'] - 2)
    page.endPage = Math.min(page['pages'], page['current'] + 2)
    // 渲染每一页
    for (let i = page.startPage; i <= page.endPage; i++) {
        if(i === page.current){ // 渲染当前页，设置一个高亮的效果
            $perPage.append(`
            <li class="page-item mx-2 active" aria-current="page">
             <a class="page-link d-block" href="${paramUpdateCurrentParam('pageNum', i)}">${i}</a>
         </li>`)
        } else {
            $perPage.append(`
             <li class="page-item mx-2" aria-current="page">
                 <a class="page-link d-block" href="${paramUpdateCurrentParam('pageNum', i)}">${i}</a>
             </li>`
            )
        }
    }
    $entry_pages.html('')
    $entry_pages.html(`
            <ul class="pagination mx-auto justify-content-center">
            <li class="align-self-center me-3 rounded-3">
                    第 ${page.current} 页 &nbsp;&nbsp; 共 ${page.pages} 页
            </li>
            <li class="page-item ms-page">
                 <a class="page-link" href="${paramUpdateCurrentParam('pageNum', 1)}">
                    首页
                 </a>
            </li>
            <!--上一页-->
           <li class="page-item ms-page">
                <a class="page-link" href="${paramUpdateCurrentParam('pageNum', page.prePage)}">上一页</a>
            </li>`
        + $perPage.html() + `
            <!--下一页-->
             <li class="page-item ms-page">
                <a class="page-link" href="${paramUpdateCurrentParam('pageNum', page.nextPage)}">下一页</a>
            </li>
            <!--最后一页-->
             <li class="page-item ms-page" href="/index.html?pageNum=${page.pages}">
                  <a class="page-link" href="${paramUpdateCurrentParam('pageNum', page.pages)}">末页</a>
             </li>` + $tail +
        `</ul>`)
    $('#textShowResult').text('共 ' + page.total + ' 条结果')

}
// 查看某个用户角色时渲染修改的模态框
function renderShowModal(btn, productId){
    clearModal(btn)
    let data = ajaxPostJSON('/product/query/' + productId)
    let $selectCategory = $('select[name="category-id"]')
    let $selectProvider =$('select[name="provider-id"]')

    let product = ajaxPostJSON('/product/query/' + productId)['product']
    let provider = product['provider']
    let category = product['category']
    $selectProvider.html(`<option value="${provider['id']}">${provider['name']}</option>`)
    $selectCategory.html(`<option value="${category['id']}">${category['name']}</option>`)
    // 添加类型
    renderModal(btn, data['product'])
    // 设置商品的图片
    $('.ms-img-product').attr('src', data['product']['img'])
}
// 编辑某个用户的角色时渲染修改的模态框
function renderEditModal(btn, productId){
    clearModal(btn)
    let data = ajaxPostJSON('/product/query/' + productId)
    let $selectCategory = $('select[name="category-id"]')
    let $selectProvider =$('select[name="provider-id"]')
    /////////// 渲染所有的商品类型
    let categories = ajaxPostJSON('/category/query')
    $selectCategory.html('')
    categories.forEach(function (category){
        $selectCategory.append(
            `<option value="${category['id']}">${category['name']}</option>`
        )
    })
    // 修改商品类型时
    $selectCategory.change(function (){
        let result = ajaxPostUpdate({
            'url': '/product/category/update/' + productId,
            'data' : {'categoryId' : $(this).val()}
        })
        if(result['code'] === CODE_SUCCESS)
            ms_show_toast(true, result['msg'])
        else
            ms_show_toast(false, result['msg'])
    })
    ///////////// 渲染所有供应商
    let provider = ajaxPostJSON('/provider/query')['records']
    console.log(provider)
    $selectProvider.html('')
    provider.forEach(function (provider){
        $selectProvider.append(
            `<option value="${provider['id']}">${provider['name']}</option>`
        )
    })

    // 修改供应商时
    $selectProvider.change(function (){
        let result = ajaxPostUpdate({
            'url': 'product/provider/update/' + productId,
            'data' : {'providerId' : $(this).val()}
        })
        if(result['code'] === CODE_SUCCESS)
            ms_show_toast(true, result['msg'])
        else
            ms_show_toast(false, result['msg'])
    })

    // 选中供应商类型和商品类型
    $selectCategory.val(ajaxPostJSON('/product/query/' + productId)['product']['categoryId'])
    $selectProvider.val(ajaxPostJSON('/product/query/' + productId)['product']['providerId'])
    // 添加类型的监听
    renderModal(btn, data['product'])
    // 选择供应商和商品类型
    renderModalWithPrefix(btn, data['provider'], 'provider-')
    renderModalWithPrefix(btn, data['product']['category'], 'category-')
    // 设置商品的图片
    $('.ms-img-product').attr('src', data['product']['img'])

}
// 点击修改商品图片后，绑定该商品ID到修改图片的弹窗
function renderProductId(){
    $('#modal-img-save').click(function (){
        saveProductImg($(this).attr('id'), $('#edit-id').val(), 400, 450)
    })
}
function renderModalInsert(btn){
    let $model = $($(btn).data('bs-target'))
    $model.children('input').val('')
    $model.children('select').val('')
    $('#modal-insert-img').attr('src', DEFAULT_IMG_INSERT_PRODUCT)

    let $selectCategory = $('select[name="categoryId"]')
    let $selectProvider =$('select[name="providerId"]')
    ///////////// 渲染所有供应商
    let provider = ajaxPostJSON('/provider/query')['records']
    $selectProvider.html('')
    provider.forEach(function (provider){
        $selectProvider.append(
            `<option value="${provider['id']}">${provider['name']}</option>`
        )
    })
    /////////// 渲染所有的商品类型
    let categories = ajaxPostJSON('/category/query')
    $selectCategory.html('')
    categories.forEach(function (category){
        $selectCategory.append(
            `<option value="${category['id']}">${category['name']}</option>`
        )
    })
}
////////////////////// 功能函数区 ///////////////////////
///// 跳转到指定页
function toPage(inputId, mini, maxi){
    $input = $('#' + inputId)
    let page = $input.val()
    // 限制页面的范围
    page = Math.min(page, maxi)
    page = Math.max(page, mini)
    location.href = paramUpdateCurrentParam('pageNum', page)
}
// 全选
$('#cb_all').click(function (){
    $('.cb_product').prop('checked', $(this).prop('checked'))
})
// 删除单个商品
function removeProduct(productId){
    if(!confirm('确认要删除吗？')) return
    let result =  ajaxDelete({
        url: '/product/delete/' + productId,
        data: ''
    })
    if(result['code'] === CODE_SUCCESS){
        ms_show_toast_reload(true, result['msg'])
    } else
        ms_show_toast(false, result['msg'])
}
// 批量删除商品
function removeProducts(){
    let ids = []
    // 获取选择的需要删除的供应商
    $('.cb_product').each(function (){
        if($(this).prop('checked') === true){
            ids.push($(this).data('id'))
        }
    })
    if(ids.length === 0) { ms_show_toast(false, '请选择需要删除的商品') ;return }
    if(!confirm('确认要删除这些吗？')) return
    let result =  ajaxDelete({
        url: '/product/delete/' + ids,
        data: ''
    })
    if(result['code'] === CODE_SUCCESS){
        ms_show_toast_reload(true, result['msg'])
    } else
        ms_show_toast(false, result['msg'])
}
// 搜索商品
function searchProduct(btn){
    location.href = paramUpdateCurrentParam('name', $(btn).prev('input').val())
}
// 修改保存商品信息
function saveProduct(form){
    let result = ajaxPostUpdate({
        url: '/product/update',
        data: $(form).serialize()
    })
    ms_show_response(result, () => {setTimeout(() => location.reload(), DELAY_TOAST_WHEN_BTN)})
}
// 选择商品图片
function selectProductImg(){
    // 添加监听
    $("input[name='img']").on('change', function (){
        let filePath = $(this).val(); //获取到input的value，里面是文件的路径
        let fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(); //获取文件后缀
        // let src = window.URL.createObjectURL(this.files[0]); //转成可以在本地预览的格式
        // 检查是否是图片
        if( !fileFormat.match(/.png|.jpg|.jpeg|.bmp|.gif/) ) {
            //error_prompt_alert
            alert('上传错误,文件格式必须为：png/jpg/jpeg/bmp/gif');
            return ;
        }
        let reader = new FileReader();
        reader.onload = function () {
            $('#modal-insert-img').attr('src', this.result); //将图片地址放置在img的src中。
        }
        reader.readAsDataURL(this.files[0]);
    }).click()
}
// 添加商品
function insertProduct(form){
    // 提交添加的请求
    let result = ajaxPostJSONByMap('/product/insert', $(form).serialize() + '&img=' + $('#modal-insert-img').attr('src'))
    if(result['code'] === CODE_SUCCESS) {
        ms_show_toast_reload(true, result['msg'])
    } else
        ms_show_toast(false, result['msg'])
}
$(document).ready(function (){
    useImgPlugin(700, 400, 700, 400)
    pageData = ajaxPostJsonByCurrentUrlParam('/product/query')
    renderProducts(pageData['records'], 100)
    renderPage(pageData)
})